﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.Supplier;
using ProduceBasicData.Domain.Material;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;
using ProduceBasicData.Api.Services;

namespace ProduceBasicData.Api.Application.Handler.Supplier
{
    /// <summary>
    /// 供应商信息录入处理
    /// </summary>
    public class CreateSupplierHandler : IRequestHandler<CreateSupplierCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<SupplierModel> supplierRepo;
        private readonly IMapper mapper;
        private readonly ICodeRuleService codeRuleService;

        public CreateSupplierHandler(IBaseRespository<SupplierModel> supplierRepo,
           IMapper mapper,ICodeRuleService codeRuleService)
        {
            this.supplierRepo = supplierRepo;
            this.mapper = mapper;
            this.codeRuleService = codeRuleService;
        }

        public async Task<ApiResult<int>> Handle(CreateSupplierCommand request, CancellationToken cancellationToken)
        {
            
            ApiResult<int> res=new ApiResult<int>();


            var model = mapper.Map<SupplierModel>(request);

            //编码
            if (string.IsNullOrEmpty(model.Code))
            {
                var code = await codeRuleService.AutoGenerateCodeAsync("ProduceBasicData.Domain.Material.SupplierModel");
                if (!string.IsNullOrEmpty(code))
                {
                    model.Code = code;
                }
                else
                {
                    model.Code = $"GYS{DateTime.Now:yyyyMMddHHmmss}";
                }
            }


            var r=await supplierRepo.AddAsync(model);
            if (r>0)
            {
                res.Data=r;
                res.Msg = "添加成功";
                res.Code=ApiEnum.Success;
            }
            else
            {
                res.Msg = "添加失败";
                res.Code = ApiEnum.Failed;
            }
            return res;
        }
    }
}
